import React, { useState, useEffect, useRef,forwardRef, useImperativeHandle } from 'react';
const tracking = window.tracking;
import _ from 'lodash';
import { useNavigate } from 'react-router-dom'
import '../../public/js/face-min';

const Login2 =forwardRef( (props,ref) => {
    const navigate = useNavigate()
    const screenshotAndUpload = () => {
        setUploadLock(false);
        const canvas = screenshotCanvasRef.current;
        const video = videoRef.current;
        const ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        const base64Img = canvas.toDataURL('image/jpeg');
    
        // 发送人脸图片到服务器进行登录验证
        fetch("http://127.0.0.1:3000/faceLogin", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ b64: base64Img.split(',')[1] }),
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(res => {
            if (res.code === 200) {
                localStorage.setItem("token", res.token);

                alert(res.msg);
                destroyed();
                navigate('/layout')
            } else if (res.code === 401 || res.code === 251) {
                alert(res.msg);
                destroyed();
            }
        })
        .catch(error => {
            destroyed();
            // console.error('There was a problem with the fetch operation:', error);
            setErrorMessage('登录失败，请重试');
        })
        .finally(() => {
            destroyed(); // 确保无论如何都会调用 destroyed
        });
    };
    const debouncedScreenshotAndUpload = _.debounce(screenshotAndUpload, 100); // 500ms 内只执行一次
    useImperativeHandle(ref, () => ({
         faceLoginBtn : () => {
            setIsShowV(true);
            init();}
    }));
    // 初始化跟踪任务状态
    const [trackerTask, setTrackerTask] = useState(null);
    // 初始化媒体流跟踪状态
    const [mediaStreamTrack, setMediaStreamTrack] = useState(null);
    // // 初始化视频元素状态
    const [video, setVideo] = useState(null);
    // 初始化截图画布状态
    const [screenshotCanvas, setScreenshotCanvas] = useState(null);
    // 初始化上传锁状态
    const [uploadLock, setUploadLock] = useState(true);
    // 初始化显示视频状态
    const [isShowV, setIsShowV] = useState(false);
    // 创建视频元素引用
    const videoRef = useRef(null);
    // 创建画布元素引用
    const canvasRef = useRef(null);
    // 创建截图画布元素引用
    const screenshotCanvasRef = useRef(null);
    // 人脸识别登录按钮点击事件处理函数
    // 初始化视频跟踪
    const init = () => {
        setVideo(videoRef.current);
        setScreenshotCanvas(screenshotCanvasRef.current);
        const canvas = canvasRef.current;
        const context = canvas.getContext('2d');
        // 创建人脸跟踪器
        const tracker = new tracking.ObjectTracker('face');
        tracker.setInitialScale(4);
        tracker.setStepSize(2);
        tracker.setEdgesDensity(0.1);
        // 获取媒体流并设置到 video 元素上
        navigator.mediaDevices.getUserMedia({ video: true })
            .then((stream) => {
                const videoElement = videoRef.current;
                videoElement.srcObject = stream;
                setMediaStreamTrack(stream); // 设置 mediaStreamTrack 状态
                // 开始跟踪视频流
                setTrackerTask(tracking.track(videoElement, tracker, { camera: true }));
            })
            .catch((error) => {
                console.error('Failed to get user media:', error);
            });
    
        // 监听跟踪事件
        tracker.on('track', (event) => {
            context.clearRect(0, 0, canvas.width, canvas.height);
            event.data.forEach((rect) => {
                context.strokeStyle = '#76e535';
                context.strokeRect(rect.x, rect.y, rect.width, rect.height);
            });
            if (uploadLock && event.data.length) {
                debouncedScreenshotAndUpload();
            }
        });
    };
    // 截图并上传人脸图片
  
    // 销毁跟踪任务并关闭摄像头
    const destroyed = () => {
        if (mediaStreamTrack) {
            const tracks = mediaStreamTrack.getTracks();
            tracks.forEach(track => track.stop());
            setMediaStreamTrack(null); // 清除 mediaStreamTrack 状态
        }
        if (trackerTask) {
            trackerTask.stop();
            setTrackerTask(null); // 清除 trackerTask 状态
        }
        setIsShowV(false);
    };

    return (
        <div className="login-wrapper">
            <div className="big-box" style={{ display: isShowV ? 'block' : 'none',width:'100vw',height:"100vh", position:'fixed', top:0,left:0 ,backgroundColor:'#fff'}}>
               <div style={{}}>
               <div className="video-box" style={{position:'relative'}}>
                    <video ref={videoRef} id="video" width="320" height="240" preload="auto" autoPlay loop muted></video>
                    <canvas ref={canvasRef} id="canvas" width="320" height="240" style={{position:'absolute',left:0}}></canvas>
                </div>
                <div className="success-face">
                    <canvas ref={screenshotCanvasRef} id="screenshotCanvas" width="320" height="240"></canvas>
                    <div className="switch-button">
                        <button type="button" onClick={()=>{destroyed()}}>关闭摄像头</button>
                        <button type="button" onClick={()=>{init()}}>开始识别</button>
                    </div>
                </div>
               </div>
            </div>
        </div>
    );
});

export default Login2;